--
-- Author: shunguo.chen
-- Date: 2017-09-11 11:32:35
--
-- LoginCreateView	创建角色面版

local AvatarFactory = app:getClass("AvatarFactory")
local TabsBtn = require("app.widget.TabsBtn")
local LoginSelectRender = import(".LoginSelectRender")

local fileName = string.getModeName(...)
local ClassRef = class(fileName, app.mvc.ViewBase)

ClassRef.VIEW_ROOT_RES = Res.LoginCreateScene

local CLASS_ARRAY = {1,2,5,4,3}

local ErrorMsg_OutOfMax = string.format(L("lua_code_text_315"), Constant.NICKNAME_MAX_LEN) 
local ErrorMsg_NotEnoughLen = string.format(L("lua_code_text_76"), Constant.NICKNAME_MIN_LEN)
local ErrorMsg_NotValid = L("lua_code_text_337")

function ClassRef:init()
    self._bgImg = self._ui["Panel/Panel_bg/Image_1"]
    self._fgImg = self._ui["Panel/Panel_bg/Image_2"]
	self._bgImg:setContentSize(display.size)
    local _, height = self._fgImg:getContentSize2()
	self._fgImg:setContentSize(cc.size(display.width, height))

	self._ui.Button_back:addClickEventListener(function()
		executeFunc(self._onOperate, "exit")
	end)
	self._ui.Button_enter:addClickEventListener(function()
		local name = self._editBox:getText()
		local ok, msg = self:_checkNameValid(name)
		if ok then
			local params = clone(self._params)
			params.fashionIDs = nil
			params.name = name
			executeFunc(self._onOperate, "enter", params)
		else
			display.pushToast(msg)
		end
	end)

	-- name editBox
	self:_initEditBox()

	-- class select
	local panel = self._ui["Panel/Panel_zhiye"]
	local btns = {0,0,0,0,0}
	local binds = {0,0,0,0,0}
	for i=1,5 do
		btns[i] = panel:getChildByName("Button_"..i)
		binds[i] = panel:getChildByName("Panel_"..i)
	end

	local function onTabsBtn(index)
    	if self._curIdx then
    		self._curIdx = index
	    	self:switchPanel()
	    else
	    	self._curIdx = index
	    end
    end
    self._tabsBtn = TabsBtn.new(btns, onTabsBtn, 1, binds)

    -- race hair face
    local panel = self._ui["Panel/Panel_image"]
    self._raceText = panel:getChildByName("Text")
    local btns = {panel:getChildByName("Button_male"), panel:getChildByName("Button_female")}
    local function onGenderTabsBtn(index)
        if self._params then
    		local curData = self._raceDatas[index]
            if curData then
        		self._curData = curData
        		self._hairRender:setDatas(curData.hairIDs)
        		self._faceRender:setDatas(curData.faceIDs)

        		self._gender = index
        		self._params.gender = index
        		self._params.hairID = curData.hairIDs[self._hairRender:getIndex()]
        		self._params.faceID = curData.faceIDs[self._faceRender:getIndex()]
        		self._params.fashionIDs = curData.fashionIDs
        		self:_refreshPlayer()
            else
                display.pushToast(L("该性别暂未开放"))
                self._genderBtn:setSelected(self._gender)
            end
    	end
    end
    self._genderBtn = TabsBtn.new(btns, onGenderTabsBtn, 1)

    self._faceRender = LoginSelectRender.create(nil, panel:getChildByName("node01"))
    self._faceRender:onBtnClick(function(data)
    	self._params.faceID = data
		self:_refreshPlayer(2)
    end)
    self._hairRender = LoginSelectRender.create(nil, panel:getChildByName("node02"))
    self._hairRender:onBtnClick(function(data)
    	self._params.hairID = data
		self:_refreshPlayer(1)
    end)
    self._hairColorRender = LoginSelectRender.create(nil, panel:getChildByName("node03"))
    self._hairColorRender:onBtnClick(function(data)
		self._params.hairColorID = data
		self:_refreshPlayer(1)
    end)

    --hero touch check
	local touchLayer = display.newLayer()
    touchLayer:setContentSize(display.width,display.height)
    touchLayer:setTouchEnabled(true)
    self:addChild(touchLayer)
	local touchListener = cc.EventListenerTouchOneByOne:create()
    touchListener:registerScriptHandler(function(touch, event)
    	local locationX,locationY = touch:getLocation2()
    	local playArmature = self._ui.player:getChildByTag(0)
    	if playArmature and playArmature:containWorldPoint(locationX,locationY) then
    		self:_playNextAnimation()
    	end
    	return false
    end,cc.Handler.EVENT_TOUCH_BEGAN)
    self:getEventDispatcher():addEventListenerWithSceneGraphPriority(touchListener, touchLayer)
end

function ClassRef:_initEditBox()
	-- name
	self._ui["Panel/Panel_name/Button_random"]:addClickEventListener(function()
		self:setRandomName()
	end)

	local function onEditCallback(strEventName,sender)
		local editbox = sender
        if strEventName == "changed" then
            -- TODO csg
        end
	end
	self._editBox = display.replaceTextFieldWithEditBox(self._ui["Panel/Panel_name/TextField"])
	self._editBox:registerScriptEditBoxHandler(onEditCallback)
end

function ClassRef:_checkNameValid(str)
    local errorMsg = nil

    local len = string.counting(str)

    if len > Constant.NICKNAME_MAX_LEN then
        errorMsg = ErrorMsg_OutOfMax
        return false,errorMsg
    end

    if len < Constant.NICKNAME_MIN_LEN then
        errorMsg = ErrorMsg_NotEnoughLen
        return false,errorMsg
    end

    local mathch = string.filter_spec_chars(str)

    if str~=mathch then
        errorMsg = ErrorMsg_NotValid
        return false,errorMsg
    end

    return true
end

function ClassRef:setRandomName()
    -- 现不需要对随机名字也检测屏蔽字
    -- executeFunc(self._onOperate, "randomName")
    local name = GD:randomNickName(Constant.NICKNAME_MAX_LEN)
    self:setName(name)
end

function ClassRef:setName(name)
	if not name then return end
	self._editBox:setText(name)
end

-- tp = nil	changeAll
-- tp = 1	changeHead
-- tp = 2	changeFace
function ClassRef:_refreshPlayer(tp)
	if not self._params then return end
	local hero = self._ui.player:getChildByTag(0)
	if tp and hero then
		if tp == 1 then
			-- 换头
			AvatarFactory.changeHead(hero, self._params)
		else
			-- 换脸
			AvatarFactory.changeFace(hero, self._params)
		end
	else
		self._ui.player:removeAllChildren()

		local hero = AvatarFactory.createHero(self._params)
		self._ui.player:addChild(hero)
		hero:setTag(0)
		hero:setPositionX(self._ui.player:getContentSize().width/2)
		self._playIndex = nil
		self:_playNextAnimation()
	end
end

local PlayerAnimations = {"mapidle","mapwalk","style1","mapmove","angry","celebrate","confusion","happy","seriously"}

function ClassRef:_playNextAnimation()
	local hero = self._ui.player:getChildByTag(0)
	if hero then
		local animations = PlayerAnimations
		if not self._playIndex or self._playIndex >= #animations then
			self._playIndex = 0
		end
		self._playIndex = self._playIndex + 1
		hero:playAni({name=animations[self._playIndex],next="mapidle"})
	end
end

function ClassRef:_refreshBg()
    local bg = self._curData.bg
    self._bgImg:setVisible(bg ~= nil)
    if bg and self._preBg ~= bg then
        self._preBg = bg
        self._bgImg:loadTexture(bg)
    end

    local fg = self._curData.fg
    self._fgImg:setVisible(fg ~= nil)
    if fg and self._preFg ~= fg then
        self._preFg = fg
        self._fgImg:loadTexture(fg)
    end
end

function ClassRef:switchPanel(raceID, gender, hairID, faceID, hairColorID)
	local classID = CLASS_ARRAY[self._curIdx]
	-- 只处理一个种族
	local data = self._datas[classID]
	if not raceID then
		for k,v in pairs(data) do
			raceID = k
			break
		end
	end
	self._raceDatas = data[raceID]

	-- race name
	self._raceText:setString(L("race_" .. raceID))

	if not self._gender then
		if not gender then
			gender = 1
			for k,v in pairs(self._raceDatas) do
				gender = k
				break
			end

			-- user real gender
			if self._info then
				if self._info.gender == L("lua_code_text_396") then
					gender = Enums.Sex.male
				elseif self._info.gender == L("lua_code_text_227") then
					gender = Enums.Sex.female
				end
			end
		end

		self._genderBtn:setSelected(gender)
		self._gender = gender
	end

	local curData = self._raceDatas[self._gender]
	self._curData = curData

	local hairIdx = hairID and table.indexof(curData.hairIDs, hairID) or 1
	local faceIdx = faceID and table.indexof(curData.faceIDs, faceID) or 1
	hairColorID = hairColorID or math.random(1, curData.hairColorMax)

	self._params = {
		classID = classID,
		raceID = raceID,
		gender = self._gender,
		hairID = curData.hairIDs[hairIdx],
		faceID = curData.faceIDs[faceIdx],
		hairColorID = hairColorID,
		fashionIDs = curData.fashionIDs
	}
	
	local faceData = {
		index = faceIdx,
		datas = curData.faceIDs,
		name = L("lua_code_text_336")
	}
	local hairData = {
		index = hairIdx,
		datas = curData.hairIDs,
		name = L("lua_code_text_308")
	}

	local colorDatas = {}
	for i=1,curData.hairColorMax do
		colorDatas[i] = i
	end
	local hairColorData = {
		index = hairColorID,
		datas = colorDatas,
		name = L("lua_code_text_281")
	}
	self._faceRender:setData(faceData)
	self._hairRender:setData(hairData)
	self._hairColorRender:setData(hairColorData)

	-- 刷新角色
	self:_refreshPlayer()
    self:_refreshBg()
end

function ClassRef:setUserInfo(info)
	self._info = info
	if info then
		self:setName(info.nickName)
	else
		self:setRandomName()
	end
end

function ClassRef:refresh(datas, battleGuideRoleId)
	self._datas = datas

	if battleGuideRoleId then
		local conf = GD:getBattleGuideConf(battleGuideRoleId)
		local gender = tonumber(conf.gender)
		local classID = tonumber(conf.classID)
		local raceID = tonumber(conf.raceID)
		local faceID = tonumber(conf.faceID)
		local hairID = tonumber(conf.hairID)
		local hairColorID = tonumber(conf.hairColorID)

		self._curIdx = table.indexof(CLASS_ARRAY, classID)
		self._tabsBtn:setSelected(self._curIdx)
		self:switchPanel(raceID, gender, hairID, faceID, hairColorID)
	else
		self._curIdx = 1
		self:switchPanel()
	end
end

function ClassRef:remove()

end

return ClassRef